package cn.fl.capital.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.fl.export.api.ICapFundExportApiService;
import cn.fl.export.condition.CapFundVfLogExportCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapFundVfLogQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.dto.CapFundVfLogDTO;
import cn.fl.capital.dto.CapFundVfLogRDTO;
import cn.fl.capital.service.ICapFundVfLogApiService;
import cn.fl.capital.service.ICapFundVfLogRApiService;
import cn.fl.capital.service.ICapFundVfLogService;
import cn.fl.capital.transform.CapFundVfLogVOTransform;
import cn.fl.capital.vo.CapFundVO;
import cn.fl.capital.vo.CapFundVfLogRVO;
import cn.fl.capital.vo.CapFundVfLogVO;
import cn.fl.framework.base.context.CurrentThreadContext;

/**
 * @Description: 资金核销冲红记录表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class CapFundVfLogServiceImpl implements ICapFundVfLogService {

	/**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(CapFundVfLogServiceImpl.class);
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private ICapFundVfLogApiService capFundVfLogApiService;
	@Autowired
	private ICapFundExportApiService capFundExportApiService;
	
	/**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

	@Override
	public CapFundVfLogVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)) return null;
		CapFundVfLogDTO dto = this.capFundVfLogApiService.selectCapFundVfLogById(id);
		return CapFundVfLogVOTransform.toVO(dto);
	}

	@Override
	public Long add(CapFundVfLogVO entity) throws BaseException{
		if(null == entity) return null;
		return this.capFundVfLogApiService.addCapFundVfLog(CapFundVfLogVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeByIds(List<Long> ids) throws BaseException{
		if(CollectionUtils.isEmpty(ids)) return false;
		return this.capFundVfLogApiService.removeCapFundVfLogByIds(ids,CurrentThreadContext.getCurrentUserId());
	}

	@Override
	public boolean modify(CapFundVfLogVO entity) throws BaseException{
		if(null == entity) return false;
		return this.capFundVfLogApiService.modifyCapFundVfLog(CapFundVfLogVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
        CapFundVfLogQueryCondition condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new CapFundVfLogQueryCondition());
        }
		condition=(CapFundVfLogQueryCondition)page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		page=this.capFundVfLogApiService.searchCapFundVfLogListPage(page);
		if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<CapFundVfLogVO> voList=CapFundVfLogVOTransform.toVOList((List<CapFundVfLogDTO>)page.getResultList());
            this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
	}
	
	@Override
	public List<CapFundVfLogVO> searchList(CapFundVfLogQueryCondition condition) throws BaseException{
		if(null == condition) condition=new CapFundVfLogQueryCondition();
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
		condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		List<CapFundVfLogVO> voList=CapFundVfLogVOTransform.toVOList(this.capFundVfLogApiService.searchCapFundVfLogList(condition));
		this.setDictData(voList);
		return voList;
	}
	
    /**
     * 添加数据字典名称
     * @param voList
     */
	public void setDictData(List<CapFundVfLogVO> voList){
		if(CollectionUtils.isEmpty(voList)) return;
		Map<String, String> vfTypCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_CAP_VF_TYP_CD);
		Map<String, String> vfWayCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_CAP_VF_WAY_CD);
		Map<String, String> vfStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), CapitalConstant.CODE_CAP_VF_STS_CD);
		for(CapFundVfLogVO vo:voList){
			if (vfTypCdMap != null && vfTypCdMap.containsKey(vo.getVfTypCd())) {
				vo.setVfTypCdNm(vfTypCdMap.get(vo.getVfTypCd()));
        	}
			if (vfWayCdMap != null && vfWayCdMap.containsKey(vo.getVfWayCd())) {
				vo.setVfWayCdNm(vfWayCdMap.get(vo.getVfWayCd()));
			}
			if (vfStsCdMap != null && vfStsCdMap.containsKey(vo.getVfStsCd())) {
				vo.setVfStsCdNm(vfStsCdMap.get(vo.getVfStsCd()));
			}
		}
	}

	/**
	 * 批量导出分解单
	 *
	 * @param condition
	 * @return
	 * @throws BaseException
	 */
	@Override
	public DataResultVO exportDecomposeList(CapFundVfLogExportCondition condition) throws BaseException {
	    if(null == condition){
	        condition = new CapFundVfLogExportCondition();
        }
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
        try {
            DataResultDTO resultDTO=this.capFundExportApiService.exportDecomposeList(condition);
            if(null==resultDTO){
                return new DataResultVO(BaseConstant.IS_YESNO_NO,"导出失败");
            }else{
                return new DataResultVO(Integer.parseInt(resultDTO.getCode()),resultDTO.getInfo(),resultDTO.getData());
            }
        } catch (BaseException e) {
            BaseLogUtils.error(logger,"exportDecomposeList","批量导出分解单失败");
			BaseLogUtils.error(logger, "-", "异常", e);
        } catch (NumberFormatException e) {
            BaseLogUtils.error(logger,"exportDecomposeList","批量导出分解单失败");
			BaseLogUtils.error(logger, "-", "异常", e);
        }
        return new DataResultVO(BaseConstant.IS_YESNO_NO,"导出失败");
    }

	
	/**
	 * 处理查询后的核销记录数据 
	 * @param funid
	 * @param list
	 * @return
	 * @throws BaseException
	 */
	@Override
	public Map<Long,Date> searchfundVHList(List<CapFundVfLogRVO> funid, List<Long> list) 
			throws BaseException {
		 Map<Long,Date> questionMap=null;
		//拿到核销id  放入数组
		List<Long>   arraylist=new  ArrayList<Long>();
		if (CollectionUtils.isNotEmpty(funid)) {
		for (CapFundVfLogRVO capFundVfLogRVO : funid) {
			  arraylist.add(capFundVfLogRVO.getVfLogId());
	       }
		//查询所有的核销记录
		List<CapFundVfLogDTO> searchfundVHList = this.capFundVfLogApiService.searchfundVHList(arraylist);
	
		if(CollectionUtils.isNotEmpty(searchfundVHList)){
			 questionMap =new HashMap<Long,Date>();
			for (int i = 0; i < funid.size(); i++) {
				Long long1 = funid.get(i).getFundId();//资金id
				Long vfLogId = funid.get(i).getVfLogId();//核销id
				for (CapFundVfLogDTO capFundVfLogDTO : searchfundVHList) {
					//相同了就放行      //这里有问题capFundVfLogDTO.getFundId()拿不到资金id
					Long id = capFundVfLogDTO.getId();
					//System.out.println(id+"<>"+vfLogId);
					if(id.equals(vfLogId)){
						if(questionMap.containsKey(long1)){//先看看集合中是否有值[资金id]
							 Date StartDate = DateUtils.formatDate(questionMap.get(long1), DateUtils.YYYY_MM_DDHHMMSS);//当前值
            				 Date endDate = DateUtils.formatDate(capFundVfLogDTO.getVfTm(), DateUtils.YYYY_MM_DDHHMMSS);//列表值
            					long daysBetweenTwoDates = DateUtils.getDaysBetweenTwoDates(StartDate,endDate);
            					if(daysBetweenTwoDates>0){
            					//等于零的时候什么都不做
            					}else if(daysBetweenTwoDates<0){
            					questionMap.put(long1, capFundVfLogDTO.getVfTm());
            					}
						}else{
							questionMap.put(long1, capFundVfLogDTO.getVfTm());//没有就添加
						}
					}
				}
			}
		}
     	}
		return questionMap;
     }
}
